function showdialog(opt) {
    let str ='<div class="dialog" style="margin-bottom:0;">'
    +'<div class="heading">';
    if (opt.title) {
        str += opt.title;
    }
    str += '</div><div style="padding:10px;">';
    if (opt.html) {
        str += opt.html;
    }
    str += '</div></div>';
    opt.html = str;
    if (opt.size && opt.size ==='small') {
        opt.width = 400;
        opt.height = 300;
    }
    showwindow(opt);
}

function showwindow(opt) {
    let win = document.getElementsByClassName('window')[0];
    if (!win) {
        $('body').append('<div class="window"><div class="winclose"><a href="javascript:void(0);" '
        +'onclick="closewin(this);">&times;</a></div></div>');
        win = document.getElementsByClassName('window')[0];
    }
    if (!opt) {
        opt ={
            width:800,
            height:600
        };
    }
    let width = (opt.width || 800);
    let left = (document.body.clientWidth- width)/2;
    let height = (opt.height || 600);
    let top = (document.body.clientHeight- height)/2;
    win.style.width= width +'px';
    win.style.height= height +'px';
    win.style.top = top +'px';
    win.style.left = left + 'px';
    $('.mask').show();
    win.style.display = 'block';
    $(win).append(opt.html ||'&nbps;' );
}

function closewin(obj) {
    obj.parentElement.parentElement.remove();
    document.getElementsByClassName("mask")[0].style.display="none";
}


//素材
var media = new Vue({
    el:'#media',
    data:{
        title:'素材管理',
        grid:{
            type:'',
            rows:[],
            offset:0, //skip
            count:20, //页长
            totalCount: 0, //总行数
            itemCount: 0//当前页行数
        },
        all:{
            voice_count:0,
            video_count:0,
            image_count:0,
            news_count:0
        }
    },
    methods:{
        getall:function () {
            let all = this.all;
            $.ajax({
                url:'https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token='+ token,
                dataType:'json',
                success:function (res) {
                    let ass = assert(res);
                    if (ass) {
                        alert(ass);
                        return;
                    }
                    all.voice_count = res.voice_count;
                    all.video_count = res.video_count;
                    all.image_count = res.image_count;
                    all.news_count = res.news_count;
                    //this.tip ='语音总数量:';
                },
                error:function () {

                }
            });
        },
        query:function (e, t) {
            $('#qtype a').removeClass('active');
            e.currentTarget.classList.add('active')
            //var t = $('#qtype').val();
            this.getlist(t, 0);
        },
        getlist:function(t, skip){
            let grid = this.grid;
            grid.type = t;
            grid.offset = skip;
            $.ajax({
                url:'https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=' + token,
                contentType: 'application/json',
                data:JSON.stringify({'type': grid.type, 'offset': grid.offset, 'count': grid.count}),
                type:'POST',
                dataType:'json',
                success:function (res) {
                    //console.log(res);
                    let ass = assert(res);
                    if (ass) {
                        alert(ass);
                        return;
                    }
                    grid.totalCount = res.total_count;
                    grid.rows = res.item;
                    //console.log(JSON.stringify(res.item[0]));
                },
                error:function (e) {

                }
            });
        },
        addtempfile:function () {
            let html='<form class="form-horizontal" enctype="multipart/form-data"><div class="form-group">'
            +'<label class="col-sm-2 control-label" for="temptype">类型</label>'
            +'<div class="col-sm-10"><select id="temptype" name="type" class="form-control">'
            +'<option value="image">图片</option><option value="voice">语音</option><option value="video">视频</option>'
            +'<option value="thumb">缩略图</option></select></div></div><div class="form-group">'
            +'<label class="col-sm-2 control-label" for="tempfile">文件</label>'
            +'<div class="col-sm-10"><input name="file1" type="file" id="tempfile"></div></div>'
            +'<div class="alert" style="word-wrap:break-word;" name="tip"></div>'
            +'<button type="button" class="btn btn-primary" onclick="media.posttempfile(this);" >'
            +'提&nbsp;交</button></form>';
            let setting ={
                title:'临时素材',
                size:'small'
            };
            setting.html = html;
            showdialog(setting);
        },
        posttempfile:function(e){
            let t = e.form.type.value;
            let tip = e.form.children.tip;
            if (!t) {
                tip.classList.add('alert-danger');
                tip.innerHTML = '无效的类型';
                return;
            }
            let files = e.form.file1.files;
            if (files && files.length < 1) {
                tip.classList.add('alert-danger');
                tip.innerHTML = '请选择文件';
                return;
            }
            let f = files[0];
            console.log(t);
            console.log(f);
            tip.classList.remove('alert-danger');
            tip.innerHTML = '';
            //api
            var fd = new FormData();
            fd.append('filename', f.name);
            fd.append('filelength', f.size);
            fd.append('content-type', f.type);
            fd.append('media', f);
            //
            $.ajax({
                url:'https://api.weixin.qq.com/cgi-bin/media/upload?access_token='+token+'&type='+ t,
                data:fd,
                type:'POST',
                contentType: false,
                processData: false,
                dataType:'json',
                success: function (res) {
                    //console.log(JSON.stringify(res));
                    var ast = assert(res);
                    if (!ast) {
                        console.log(res);
                        tip.classList.add('alert-success');
                        tip.innerHTML = JSON.stringify(res);
                        return;
                    }
                    alert(ast)
                },
                error: function (er) {

                }
            });
        },
        addfile:function () {
            let html='<form class="form-horizontal" enctype="multipart/form-data"><div class="form-group">'
            +'<label class="col-sm-2 control-label" for="temptype">类型</label>'
            +'<div class="col-sm-10"><select id="temptype" name="type" class="form-control">'
            +'<option value="image">图片</option><option value="voice">语音</option><option value="video">视频</option>'
            +'<option value="thumb">缩略图</option></select></div></div><div class="form-group">'
            +'<label class="col-sm-2 control-label" for="tempfile">文件</label>'
            +'<div class="col-sm-10"><input name="file1" type="file" id="tempfile"></div></div>'
            +'<div class="alert" style="padding:3px; margin-bottom:5px; word-wrap:break-word;" name="tip"></div>'
            +'<button type="button" class="btn btn-primary" onclick="media.postfile(this);" >'
            +'提&nbsp;交</button></form>';
            let setting = {
                title:'新增永久素材',
                size:'small'
            };
            setting.html = html;
            showdialog(setting);
        },
        postfile:function(e){
            let t = e.form.type.value;
            let tip = e.form.children.tip;
            if (!t) {
                tip.classList.add('alert-danger');
                tip.innerHTML = '无效的类型';
                return;
            }
            let files = e.form.file1.files;
            if (files && files.length < 1) {
                tip.classList.add('alert-danger');
                tip.innerHTML = '请选择文件';
                return;
            }
            let f = files[0];
            console.log(t);
            console.log(f);
            tip.classList.remove('alert-danger');
            tip.innerHTML = '';
            //api
            var fd = new FormData();
            fd.append('filename', f.name);
            fd.append('filelength', f.size);
            fd.append('content-type', f.type);
            fd.append('media', f);
            //
            $.ajax({
                url:'https://api.weixin.qq.com/cgi-bin/material/add_material?access_token='+token+'&type='+ t,
                data:fd,
                type:'POST',
                contentType: false,
                processData: false,
                dataType:'json',
                success: function (res) {
                    //console.log(JSON.stringify(res));
                    var ast = assert(res);
                    if (!ast) {
                        console.log(res);
                        tip.classList.add('alert-success');
                        tip.innerHTML = JSON.stringify(res);
                        return;
                    }
                    alert(ast)
                },
                error: function (er) {

                }
            });
        },
        addnews:function () {

        },
        shownews:function (i) {
            let row = this.grid.rows[i];
            let setting = {
                title:'news'
            };
            let str ='<div class="panel panel-default" style="margin-bottom:0;">'
            +'<div class="panel-heading">图文详情</div>'
            +'<div class="panel-body" style="max-height:557px;overflow-y:scroll;">';

            if (row.content.news_item.length> 0) {
                for (let i = 0; i < row.content.news_item.length; i++) {
                    let c = row.content.news_item[i];
                    let s ='<div style="margin-bottom:10px;">';
                    s += '<div class="row border-bottom"><div class="col-sm-2">标题：</div><div class="col-sm-10 wrap">'+c.title+'</div></div>';
                    s += '<div class="row border-bottom"><div class="col-sm-2">作者：</div><div class="col-sm-10 wrap">'+c.author+'</div></div>';
                    s += '<div class="row border-bottom"><div class="col-sm-2">摘要：</div><div class="col-sm-10 wrap">'+c.digest+'</div></div>';
                    s += '<div class="row border-bottom"><div class="col-sm-2">封面：</div><div class="col-sm-10 wrap">'+(c.show_cover_pic? "有封面":"无封面")+'</div></div>';
                    s += '<div class="row border-bottom"><div class="col-sm-2">配图：</div><div class="col-sm-10 wrap">'+c.thumb_url+'</div></div>';
                    s += '<div class="row border-bottom"><div class="col-sm-2">素材：</div><div class="col-sm-10 wrap">'+c.thumb_media_id+'</div></div>';
                    s += '<div class="row border-bottom"><div class="col-sm-2">原文：</div><div class="col-sm-10 wrap"><a target="_blank" href="'+c.content_source_url+'">'+c.content_source_url+'</a></div></div>';
                    s += '<div class="row border-bottom"><div class="col-sm-2">连接：</div><div class="col-sm-10 wrap"><a target="_blank" href="'+c.url+'">'+c.url+'</a></div></div>';
                    s += '</div>';
                    str += s;
                }
            }
            str = str + '</div></div>';
            setting.html = str;
            showwindow(setting);
        },
        deletemedia: function(id){
            if (!confirm('确认删除吗？','提示')) {
                return;
            }
            let grid = this.grid;
            let callback = this.getlist;
            $.ajax({
                url:'https://api.weixin.qq.com/cgi-bin/material/del_material?access_token='+ token,
                contentType:'application/json',
                data: JSON.stringify( {"media_id": id}),
                type:'POST',
                dataType:'json',
                success:function(res) {
                    var ast = assert(res);
                    if (!ast) {
                        console.log(res);
                        if (res.errcode == 0) {
                            callback(grid.type, grid.offset);
                        }
                        return;
                    }
                    alert(ast)
                }
            });

        }
    }
});

function refreshToken() {
    $.ajax({
        url:'http://a.fangjinnet.com/wechatfunction/GetAccessToken',
        data:{},
        type:'GET',
        async: false,//需要完成在所有接口之前
        dataType:'json',
        success:function(res){
            if (res.token) {
                token = res.token;
            }
            else {
                console.log('refreshToken no result');
            }
        },
        error:function (e) {
            console.log('error');
        }
    });
}

function assert(data){
    if (data.errcode) {
        let code = data.errcode;
        let msg = '';
        switch (code) {
            case 40001:
                msg = 'access_token无效;请重试;';
                break;
            case 40002:
                msg = '不合法的凭证类型';
                break;
            case 40003:
                msg = '不合法的OpenID';
                break;

            case 40004:
                msg = '不合法的媒体文件类型';
                break;

            case 40005:
                msg = '不合法的文件类型';
                break;

            case 40006:
                msg = '不合法的文件大小';
                break;

            case 40007:
                msg = '不合法的媒体文件id';
                break;

            case 40008:
                msg = '不合法的消息类型';
                break;

            case 40009:
                msg = '不合法的图片文件大小';
                break;

            case 40010:
                msg = '不合法的语音文件大小';
                break;

            case 40011:
                msg = '不合法的视频文件大小';
                break;

            case 40012:
                msg = '不合法的缩略图文件大小';
                break;

            case 40013:
                msg = '不合法的AppID，请开发者检查AppID的正确性，避免异常字符，注意大小写';
                break;

            case 40014:
                msg = '不合法的access_token，请开发者认真比对access_token的有效性（如是否过期），或查看是否正在为恰当的公众号调用接口';
                break;

            case 40015:
                msg = '不合法的菜单类型';
                break;

            case 40016:
                msg = '不合法的按钮个数';
                break;

            case 40017:
                msg = '不合法的按钮个数';
                break;

            case 40018:
                msg = '不合法的按钮名字长度';
                break;

            case 40019:
                msg = '不合法的按钮KEY长度';
                break;

            case 40020:
                msg = '不合法的按钮URL长度';
                break;

            case 40021:
                msg = '不合法的菜单版本号';
                break;

            case 40022:
                msg = '不合法的子菜单级数';
                break;

            case 40023:
                msg = '不合法的子菜单按钮个数';
                break;

            case 40024:
                msg = '不合法的子菜单按钮类型';
                break;

            case 40025:
                msg = '不合法的子菜单按钮名字长度';
                break;

            case 40026:
                msg = '不合法的子菜单按钮KEY长度';
                break;

            case 40027:
                msg = '不合法的子菜单按钮URL长度';
                break;

            case 40028:
                msg = '不合法的自定义菜单使用用户';
                break;

            case 40029:
                msg = '不合法的oauth_code';
                break;

            case 40030:
                msg = '不合法的refresh_token';
                break;

            case 40031:
                msg = '不合法的openid列表';
                break;

            case 40032:
                msg = '不合法的openid列表长度';
                break;

            case 40033:
                msg = '不合法的请求字符，不能包含\\uxxxx格式的字符';
                break;

            case 40035:
                msg = '不合法的参数';
                break;

            case 40038:
                msg = '不合法的请求格式';
                break;

            case 40039:
                msg = '不合法的URL长度';
                break;

            case 40050:
                msg = '不合法的分组id';
                break;

            case 40051:
                msg = '分组名字不合法';
                break;

            case 40060:
                msg = '删除单篇图文时，指定的 article_idx 不合法';
                break;

            case 40117:
                msg = '分组名字不合法';
                break;

            case 40118:
                msg = 'media_id大小不合法';
                break;

            case 40119:
                msg = 'button类型错误';
                break;

            case 40120:
                msg = 'button类型错误';
                break;

            case 40121:
                msg = '不合法的media_id类型';
                break;

            case 40132:
                msg = '微信号不合法';
                break;

            case 40137:
                msg = '不支持的图片格式';
                break;

            case 40155:
                msg = '请勿添加其他公众号的主页链接';
                break;

            case 41001:
                msg = '缺少access_token参数';
                break;

            case 41002:
                msg = '缺少appid参数';
                break;

            case 41003:
                msg = '缺少refresh_token参数';
                break;

            case 41004:
                msg = '缺少secret参数';
                break;

            case 41005:
                msg = '缺少多媒体文件数据';
                break;

            case 41006:
                msg = '缺少media_id参数';
                break;

            case 41007:
                msg = '缺少子菜单数据';
                break;

            case 41008:
                msg = '缺少oauth code';
                break;

            case 41009:
                msg = '缺少openid';
                break;

            case 42001:
                msg = 'access_token超时，请检查access_token的有效期，请参考基础支持-获取access_token中，对access_token的详细机制说明';
                break;

            case 42002:
                msg = 'refresh_token超时';
                break;

            case 42003:
                msg = 'oauth_code超时';
                break;

            case 42007:
                msg = '用户修改微信密码，accesstoken和refreshtoken失效，需要重新授权';
                break;

            case 43001:
                msg = '需要GET请求';
                break;

            case 43002:
                msg = '需要POST请求';
                break;

            case 43003:
                msg = '需要HTTPS请求';
                break;

            case 43004:
                msg = '需要接收者关注';
                break;

            case 43005:
                msg = '需要好友关系';
                break;

            case 43019:
                msg = '需要将接收者从黑名单中移除';
                break;

            case 44001:
                msg = '多媒体文件为空';
                break;

            case 44002:
                msg = 'POST的数据包为空';
                break;

            case 44003:
                msg = '图文消息内容为空';
                break;

            case 44004:
                msg = '文本消息内容为空';
                break;

            case 45001:
                msg = '多媒体文件大小超过限制';
                break;

            case 45002:
                msg = '消息内容超过限制';
                break;

            case 45003:
                msg = '标题字段超过限制';
                break;

            case 45004:
                msg = '描述字段超过限制';
                break;

            case 45005:
                msg = '链接字段超过限制';
                break;

            case 45006:
                msg = '图片链接字段超过限制';
                break;

            case 45007:
                msg = '语音播放时间超过限制';
                break;

            case 45008:
                msg = '图文消息超过限制';
                break;

            case 45009:
                msg = '接口调用超过限制';
                break;

            case 45010:
                msg = '创建菜单个数超过限制';
                break;

            case 45011:
                msg = 'API调用太频繁，请稍候再试';
                break;

            case 45015:
                msg = '回复时间超过限制';
                break;

            case 45016:
                msg = '系统分组，不允许修改';
                break;

            case 45017:
                msg = '分组名字过长';
                break;

            case 45018:
                msg = '分组数量超过上限';
                break;

            case 45047:
                msg = '客服接口下行条数超过上限';
                break;

            case 46001:
                msg = '不存在媒体数据';
                break;

            case 46002:
                msg = '不存在的菜单版本';
                break;

            case 46003:
                msg = '不存在的菜单数据';
                break;

            case 46004:
                msg = '不存在的用户';
                break;

            case 47001:
                msg = '解析JSON/XML内容错误';
                break;

            case 48001:
                msg = 'api功能未授权，请确认公众号已获得该接口，可以在公众平台官网-开发者中心页中查看接口权限';
                break;

            case 48002:
                msg = '粉丝拒收消息（粉丝在公众号选项中，关闭了“接收消息”）';
                break;

            case 48004:
                msg = 'api接口被封禁，请登录mp.weixin.qq.com查看详情';
                break;

            case 48005:
                msg = 'api禁止删除被自动回复和自定义菜单引用的素材';
                break;

            case 48006:
                msg = 'api禁止清零调用次数，因为清零次数达到上限';
                break;

            case 50001:
                msg = '用户未授权该api';
                break;

            case 50002:
                msg = '用户受限，可能是违规后接口被封禁';
                break;

            case 61451:
                msg = '参数错误(invalid parameter)';
                break;

            case 61452:
                msg = '无效客服账号(invalid kf_account)';
                break;

            case 61453:
                msg = '客服帐号已存在(kf_account exsited)';
                break;

            case 61454:
                msg = '客服帐号名长度超过限制(仅允许10个英文字符，不包括@及@后的公众号的微信号)(invalid   kf_acount length)';
                break;

            case 61455:
                msg = '客服帐号名包含非法字符(仅允许英文+数字)(illegal character in     kf_account)';
                break;

            case 61456:
                msg = '客服帐号个数超过限制(10个客服账号)(kf_account count exceeded)';
                break;

            case 61457:
                msg = '无效头像文件类型(invalid   file type)';
                break;

            case 61450:
                msg = '系统错误(system error)';
                break;

            case 61500:
                msg = '日期格式错误';
                break;

            case 65301:
                msg = '不存在此menuid对应的个性化菜单';
                break;

            case 65302:
                msg = '没有相应的用户';
                break;

            case 65303:
                msg = '没有默认菜单，不能创建个性化菜单';
                break;

            case 65304:
                msg = 'MatchRule信息为空';
                break;

            case 65305:
                msg = '个性化菜单数量受限';
                break;

            case 65306:
                msg = '不支持个性化菜单的帐号';
                break;

            case 65307:
                msg = '个性化菜单信息为空';
                break;

            case 65308:
                msg = '包含没有响应类型的button';
                break;

            case 65309:
                msg = '个性化菜单开关处于关闭状态';
                break;

            case 65310:
                msg = '填写了省份或城市信息，国家信息不能为空';
                break;

            case 65311:
                msg = '填写了城市信息，省份信息不能为空';
                break;

            case 65312:
                msg = '不合法的国家信息';
                break;

            case 65313:
                msg = '不合法的省份信息';
                break;

            case 65314:
                msg = '不合法的城市信息';
                break;

            case 65316:
                msg = '该公众号的菜单设置了过多的域名外跳（最多跳转到3个域名的链接）';
                break;

            case 65317:
                msg = '不合法的URL';
                break;

            case 9001001:
                msg = 'POST数据参数不合法';
                break;

            case 9001002:
                msg = '远端服务不可用';
                break;

            case 9001003:
                msg = 'Ticket不合法';
                break;

            case 9001004:
                msg = '获取摇周边用户信息失败';
                break;

            case 9001005:
                msg = '获取商户信息失败';
                break;

            case 9001006:
                msg = '获取OpenID失败';
                break;

            case 9001007:
                msg = '上传文件缺失';
                break;

            case 9001008:
                msg = '上传素材的文件类型不合法';
                break;

            case 9001009:
                msg = '上传素材的文件尺寸不合法';
                break;

            case 9001010:
                msg = '上传失败';
                break;

            case 9001020:
                msg = '帐号不合法';
                break;

            case 9001021:
                msg = '已有设备激活率低于50%，不能新增设备';
                break;

            case 9001022:
                msg = '设备申请数不合法，必须为大于0的数字';
                break;

            case 9001023:
                msg = '已存在审核中的设备ID申请';
                break;

            case 9001024:
                msg = '一次查询设备ID数量不能超过50';
                break;

            case 9001025:
                msg = '设备ID不合法';
                break;

            case 9001026:
                msg = '页面ID不合法';
                break;

            case 9001027:
                msg = '页面参数不合法';
                break;

            case 9001028:
                msg = '一次删除页面ID数量不能超过10';
                break;

            case 9001029:
                msg = '页面已应用在设备中，请先解除应用关系再删除';
                break;

            case 9001030:
                msg = '一次查询页面ID数量不能超过50';
                break;

            case 9001031:
                msg = '时间区间不合法';
                break;

            case 9001032:
                msg = '保存设备与页面的绑定关系参数错误';
                break;

            case 9001033:
                msg = '门店ID不合法';
                break;

            case 9001034:
                msg = '设备备注信息过长';
                break;

            case 9001035:
                msg = '设备申请参数不合法';
                break;

            case 9001036:
                msg = '查询起始值begin不合法';
                break;
    }
    return ' ' + code+',' +msg;
  }
  return null;
}
